import sys
from PyQt5.QtWidgets import QApplication,QWidget
from PyQt5 import QtWidgets
from PyQt5.QtCore import QStringListModel
import os
from clientui import Ui_Client
from LLone import grammar
import socket

class MainWidgets(QWidget,Ui_Client):

    mysocket = None
    datasstr = None

    def initSocket(self):
        try:
            # create an AF_INET, STREAM socket (TCP)
            self.mysocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        except socket.error as msg:
            self.textEdit.setText('Failed to create socket. Error code: ' + str(msg[0]) + ' , Error message : ' + msg[1])
            sys.exit()
        self.textEdit.setText('Socket Created')

    def __init__(self):
        super(MainWidgets, self).__init__()
        self.setupUi(self)
        self.initSocket()
        self.DOCONNECT.clicked.connect(self.connectServer)
        self.sent.clicked.connect(self.sentClicked)
        self.receive.clicked.connect(self.receiveClicked)
        self.CLOSE.clicked.connect(self.closeConnect)
        self.OPENFILE.clicked.connect(self.openfileClicked)

    def openfileClicked(self):
        strPath, fileType = QtWidgets.QFileDialog.getOpenFileName(self, "选取文件", os.getcwd(),"All Files(*);;Text Files(*.txt)")
        with open(strPath,mode='r',encoding='utf-8') as file:
            self.datasstr = file.read()

            l = self.datasstr.split('\n')

            model = QStringListModel()
            model.setStringList(l)
            self.INPUT.setModel(model)


    def closeConnect(self):
        self.mysocket.close()
        self.textEdit.append('Close!')

    def sentClicked(self):
        message = self.datasstr + '\n' + self.LINETEXT.text()
        try:
            # Set the whole string
            self.mysocket.sendall(message.encode("utf-8"))
        except socket.error:
            self.textEdit.append('Send failed')
            sys.exit()
        self.textEdit.append('Message send successfully')


    def receiveClicked(self):
        receiveme = self.mysocket.recv(4096).decode('utf-8')
        self.OUTPUT.setText(receiveme)

    def connectServer(self):
        # 定义IP地址和端口号
        host = '127.0.0.1' #'192.168.31.129'
        port = 8881
        try:
            remote_ip = socket.gethostbyname(host)
        except socket.gaierror:
            # could not resolve
            self.textEdit.append('Hostname could not be resolved. Exiting')
            sys.exit()
        self.textEdit.append('Ip address of ' + host + ' is ' + remote_ip)
        # Connect to remote server
        self.mysocket.connect((remote_ip, port))
        self.textEdit.append('Socket Connected to ' + host + ' on ip ' + remote_ip)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = MainWidgets()
    w.show()
    sys.exit(app.exec_())